<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}" class="supplier-container">
    <div :class="{'mobile-supplier-main':showMobilePage}" class="supplier-main no-margin mobile-radius">
      <template v-if="!permissionDenied">
        <Step v-if="!showMobilePage" :process="process" :detail-data="detailData" />
        <!-- 状态图标 pageStatus: 状态, 等待(0) 完成(1) 撤回(2) -->
        <div v-if="status === 1 || status === 2" class="status-icon">
          <img :src="status === 1?success:close" alt="success">
        </div>
        <!-- 每一步功能写在这 -->
        <template v-if="!isLoadDetail">
          <!-- 请款审批 -->
          <settlement-audit
            v-if="isSettlementAudit || isSettlementComplete"
            ref="settlementAudit"
            :is-closed="status === 2"
            :is-settlement-complete="isSettlementComplete"
            :settle-id="settleId"
            :supplier-id="supplierId"
            :supplier-data="supplierData"
            :process="process"
            :cost-belong="costBelong"
            :detail-data="detailData"
            :new-widthdraw="newWidthdraw"
            :is-not-order="isNotOrder"
            @updateDetail="updateDetail"
            @changeChannelName="changeChannelName"
          />
        </template>
        <div v-loading="true" v-else class="load-box">
          <empty-placeholder text="加载中..." />
        </div>
      </template>
      <div v-else class="flex">
        <DeniedPlaceholder />
      </div>
    </div>
    <el-image
      v-if="detailData.isExpedited && (detailData.isExpedited === 1 || detailData.isExpedited === 2)"
      :src="detailData.isExpedited === 1?pressImg:pressCancelImg"
      class="press-img"/>
  </div>
</template>
<script>
import { mapState } from 'vuex';
// api
import { getSupplierDetail, supplierInfo } from '@/api/supplier';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
// utils
import { decrypt } from '@/utils';
import schedule from '@/mixins/schedule';
// components
import Step from '@/components/SupplierComponent/step';
import SettlementAudit from '@/components/SupplierComponent/settlementAudit';
// png
import success from '@/assets/auditProcess/process_status_4.png';
import close from '@/assets/auditProcess/process_status_6.png';
import pressImg from '@/assets/press_top.png';
import pressCancelImg from '@/assets/press_cancel.png';

export default {
  components: {
    Step,
    SettlementAudit,
    EmptyPlaceholder
  },
  provide() {
    return {
      // 协作订单刷新数据用
      freshDetail: () => {
        this.getDetail(true);
        if (this.$refs.settlementAudit) this.$refs.settlementAudit.freshDetail();
      }
    };
  },
  mixins: [schedule],
  data() {
    return {
      pressImg, pressCancelImg,
      close, success,
      costBelong: 0, // 成本归属
      supplierId: '',
      settleId: '',
      detailData: {},
      isLoadDetail: true,
      supplierData: {},
      process: 0, // 控制进度条, 成本选择(0) 审批项选择(1) 请款审批(2) 结算完成(4)
      newWidthdraw: {},
      permissionDenied: false, // 详情页是否可查看
      status: null, // 状态, 等待(0) 完成(1) 撤回(2)
      firstInit: true,
      isNotOrder: false // 是否非订单请款
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isSettlementAudit() {
      return this.process === 2 || (this.process === 3 && this.status === 2);
    },
    isSettlementComplete() {
      return this.process === 4 && this.status === 1;
    },
    isInvite() {
      return !!this.$route.query.isInvite;
    }
  },

  watch: {
    status: {
      handler(newVal) {
        if (newVal && (this.process === 4 && newVal === 2)) {
          this.process = 2;
        }
      },
      immediate: true
    }
  },
  created() {
    this.supplierId = this.$route.query.id || 0; // 供应商id
    const isSettle = this.$route.query.isSettle || false;
    this.settleId = Number(this.$route.query.settleId) || 0; // 结算id

    // 填入成本来源
    if (this.$route.query.costBelong || this.$route.query.costBelong === 0) {
      this.costBelong = Number(this.$route.query.costBelong); // 订单编号
    }

    if (!isSettle && this.supplierId) {
      this.getSupplierInfo();
    }
    if (this.settleId && !this.isInvite) {
      // 订单请款
      this.getDetail();
    } else if (this.settleId && this.isInvite) {
      const inviteCode = decrypt(this.$route.query.isInvite);
      if (inviteCode && Number(inviteCode) === this.settleId) {
        this.getDetail();
      } else {
        this.permissionDenied = true;
      }
    }
  },
  methods: {
    // 获取供应商详情
    getSupplierInfo() { // 从供应商管理页面进入跳转获取供应商信息
      supplierInfo(this.supplierId, { costBelong: this.costBelong }).then(res => {
        if (res.code === 200) {
          res.data.id = this.supplierId;
          this.supplierData = res.data;
        }
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
      });
    },
    // 详情历史记录变更供应商详情
    changeChannelName(channelName = '') {
      this.supplierData.supplier = channelName;
    },
    updateDetail() {
      if (this.settleId !== null && this.settleId !== undefined) {
        this.getDetail();
      }
    },
    getProcessDetail(process) {
      if (this.detailData.processDetail) {
        const result = this.detailData.processDetail.find(i => {
          return i.process === process;
        });
        return result;
      }
      return null;
    },
    // 获取结算详情
    getDetail(freash) {
      const params = {};
      if (!freash) this.isLoadDetail = true;
      if (this.isInvite) {
        params.isPermission = false;
      }
      return getSupplierDetail(this.settleId, params).then(res => {
        this.isLoadDetail = false;
        if (res.code === 200) {
          this.process = res.data.process;
          this.isNotOrder = res.data.isNotOrder;
          this.detailData = res.data;
          this.costBelong = res.data.costBelong || 0;
          if (!this.supplierId) this.supplierId = res.data.supplierId;
          this.setCommentCount(res.data.commentCount);
          this.newWidthdraw = res.data.newWidthdraw ? res.data.newWidthdraw : null;
          if (res.data.isDraft) {
            this.newWidthdraw.isDraft = true;
          }
          const { supplier, costBelong, createUser, linkResource, payAmount, departmentName, actualAmount, creatorId } = res.data;
          this.supplierData = {
            supplier,
            createUser,
            creatorId,
            linkResource,
            payAmount,
            departmentName,
            actualAmount,
            costBelong
          };
          this.costBelong = costBelong || 0;
          // 用于判断结算单完成之后展示的icon
          this.status = this.getProcessDetail(this.process).status;
          this.handleShowCommentDialog();
        }
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.isLoadDetail = false;
      });
    },
    // 待办跳转打开评论
    handleShowCommentDialog() {
      if (!this.firstInit) return;
      this.firstInit = false;
      if (this.$route.query.openComment) {
        this.$nextTick(() => {
          this.$refs['settlementAudit'] && this.$refs['settlementAudit'].showProcess();
        });
      }
    },
    // 设置评论数量
    setCommentCount(count) {
      const countNum = Number(count);
      const resultNum = isNaN(countNum) ? 0 : countNum;
      this.$refs['settlementAudit'] && (this.$refs['settlementAudit'].commentTotal = resultNum);
    }
  }
};
</script>

<style lang="scss" scoped>
.mobile-detail-wrap {
  ::v-deep .table-box {
    padding-left: 12px !important;
    padding-right: 12px !important;
  }

}
.supplier-container {
  position: relative;
  min-height: calc(100vh - 56px);
  display: flex;
  flex-direction: column;
  .press-img{
    position: absolute;
    width: 86px;
    height: 75px;
    top: 16px;
    left: 16px;
    z-index: 999;
  }
}
.supplier-main {
  position: relative;
  flex: 1;
  margin: 16px;
  background-color: #fff;
  padding-bottom: 55px;
  .status-icon {
    position: absolute;
    top: 64px;
    right: 30px;
    z-index: 100;
    width: 80px;
    height: 80px;
    img {
      width: 100%;
    }
  }
}
.mobile-supplier-main {
  ::v-deep {
    .mobile-order-select {
      padding: 0 12px !important;
    }
    .supplier-wdithdraw-dialog {
      padding: 0 !important;
    }
  }
}
</style>
